package com.softa.web.controller.system;

import com.softa.bean.JsonRes;
import com.softa.dao.mapper.relation.system.SysFileRelationMapper;
import com.softa.dao.model.SysFile;
import com.softa.enummodel.FileTypeEnum;
import com.softa.utils.CommonUtil;
import com.softa.utils.DateUtils;
import com.softa.utils.FileUtil;
import com.softa.web.controller.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Map;

/**
 * 上传
 * @author yangl
 *
 */
@Controller
@RequestMapping(value="/fileUpload")
public class FileUploadController extends BaseController {

	@Autowired
	private SysFileRelationMapper sysFileRelationMapper;

	/**
	 * 重新命名
	 * @param name 原文件名
	 * @return 重新命名后的名称
	 */
	public String getNewFileName(String name){
		//获取后缀
		String suffix=name.split("\\.")[1];
    	// 生成随机文件名：当前年月日时分秒+五位随机数（为了在实际项目中防止文件同名而进行的处理）
		String rannum = CommonUtil.getRandomNumber(5); // 获取随机数
		return DateUtils.getyyyyMMddHHmmss(new Date())+rannum+"."+suffix;
	}
	
	@RequestMapping(value="/upload")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file) throws Exception{
		    String newFileName=null;
		    if(!file.isEmpty()){
		    	//获取文件名
		    	String realFileName=file.getOriginalFilename();
		    	//重命名文件
		    	newFileName=this.getNewFileName(realFileName);
		    	//文件路径
		    	//String path=request.getSession().getServletContext().getRealPath("/")+"upload/";
		    	String path=CommonUtil.getPath();
		    	File f=new File(path+newFileName);
		    	//判断文件夹是否存在，不存在则创建
		    	if(!f.exists()){
		    		f.mkdirs();
		    	}
		    	//上传
			    file.transferTo(f);
		    }
		return newFileName;
	}
	
	@RequestMapping(value="/upload1")
	@ResponseBody
	public void upload(HttpServletRequest request,HttpServletResponse response){
		MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
		CommonsMultipartFile file=(CommonsMultipartFile)multipartRequest.getFile("file");
		String name=multipartRequest.getParameter("name");
		System.out.println("name："+name);
		//获得文件名
		String realFileName=file.getOriginalFilename();
		System.out.println("文件名："+realFileName);
		//获取路径
		String ctxPath=request.getSession().getServletContext().getRealPath("/")+"upload/";
		//创建文件
		File dirPath=new File(ctxPath);
		if(!dirPath.exists()){
			dirPath.mkdirs();
		}
		File uploadFile = new File(ctxPath + realFileName);
		PrintWriter pw=null;
        try {
			FileCopyUtils.copy(file.getBytes(), uploadFile);
			response.setContentType("text/html;charset=utf-8");
			pw=response.getWriter();
			pw.write(realFileName);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}finally{
			pw.close();
		}
	}

	@RequestMapping(value="/webupload")
	@ResponseBody
	public JsonRes saveUploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
		OutputStream os = null;
		InputStream is = null;
		JsonRes json = new JsonRes();
		try {
			String contentType = file.getContentType();
//			String name = file.getName();
			long size = file.getSize();
			is = file.getInputStream();
			String originalFilename = file.getOriginalFilename();
			Map<String, String[]> parMap = request.getParameterMap();

			String filePath = "";
//			String relativepath = "";
//			String fileFileName = (String) request.getAttribute("fileFileName");
			//文件的后缀
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			//文件路径
			filePath =CommonUtil.getPath();

			String fileType = FileUtil.getFileSaveBaseDir(contentType);
			filePath = filePath + "/"+fileType+"/";

//			relativepath = "/images/";

			File newf = new File(filePath);
			if (!newf.exists()) {
				newf.mkdirs();
			}
			// 生成随机文件名：当前年月日时分秒+五位随机数（为了在实际项目中防止文件同名而进行的处理）
			// 文件重命名后的名字
			String newFileName = this.getNewFileName(originalFilename);
			String bPath = filePath  + newFileName;
//			relativepath += newFileName;
			os = new FileOutputStream(bPath);
			byte buffer[] = new byte[1024];
			int count = 0;
			long fileLen=0;
			while ((count = is.read(buffer)) > 0) {
				os.write(buffer, 0, count);
				fileLen+=count;
			}

			SysFile sysFile = new SysFile();
			sysFile.setPath(newFileName);
			sysFile.setDocName(originalFilename);
			sysFile.setSize(size);
			sysFile.setFileType(fileType);
			sysFile.setContentType(contentType);
			sysFileRelationMapper.insertSelective(sysFile);
			Long id = sysFile.getId();
			json.setId(id);
		} catch (Exception ex) {
			ex.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				os.flush();
				os.close();
			}
			if (is != null) {
				os.flush();
				is.close();
			}
		}
		return json;
	}

}
